#include <queue>
#include <utility>
#include <vector>
using namespace std;

class Solution
{
    typedef pair<int, int> PII;
    int dx[4] = {-1,1,0,0};//上下左右，纵轴
    int dy[4] = {0,0,-1,1};//横轴，左上角为原点
public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color)
    {
        int prev = image[sr][sc];
        if(prev == color)   return image;
        queue<PII> q;
        q.emplace(sr, sc);

        int rows = image.size(), cols = image[0].size();
        while(!q.empty())
        {
            auto [a, b] = q.front();
            q.pop();
            image[a][b] = color;

            for(int i=0; i<4; i++)
            {
                int x = a+dx[i], y = b+dy[i];
                if(x>=0 && x<rows && y>=0 && y<cols && image[x][y]==prev)
                {
                    q.emplace(x, y);
                }
            }
        }
        return image;
    }
};